// pages/ip/index.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: '',
    ids: '',
    userHost: [],
    defaultText: '加载中...',
    loadProgress: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.getUserHost()
    const me = this
    wx.getSystemInfo({
      success: function (res) {
        console.log(res)
        let scrollH = parseInt((res.windowHeight - 108) / res.windowHeight * 100)
        me.setData({
          pageInfo: {
            scrollHeight: scrollH,
            rowHeight: 47,
            startIndex: null,
            scrollY: true,
            readyPlaceIndex: null,
            startY: 0,
            selectedIndex: null,
          }
        })
      },
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.onLoad()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  getUserHost: function() {
    const me = this
    const open_id = app.globalData.openId
    this.setData({
      modalName: null
    })
    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: app.globalData.host + 'ip/getUserHost',
      method: 'POST',
      data: {
        open_id: open_id
      },
      success(res) {
        if (res.data.status === 'success') {
          const list = res.data.data
          const defaultText = list.length > 0 ? me.data.defaultText : '暂无数据'
          me.setData({
            userHost: list,
            defaultText: defaultText
          })
        }
      },
      complete(res){
        wx.hideLoading()
      }
    })
  },
  delItem: function(e){
    const id = e.target.dataset.id
    this.delHost(id)
  },
  delHost: function(id) {
    const me = this;
    wx.showModal({
      title: '删除确认',
      content: '同时从定时列表里删除,确认要删除？',
      confirmColor: '#FF3030',
      success(res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.host + 'ip/delUserHost',
            method: 'POST',
            data: {
              id: id
            },
            success(res) {
              if (res.data.status === 'success') {
                me.getUserHost()
                wx.showToast({
                  title: res.data.msg
                })
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none'
                })
              }
            }
          })
        }else{
          me.setData({
            modalName: null
          })
        }
      }
    })
  },
  checkIp(e) {
    const me = this
    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: app.globalData.host + 'ip/ping',
      method: 'POST',
      data: e.target.dataset,
      success(res) {
        wx.showModal({
          showCancel: false,
          title: '查询结果',
          content: '地址：' + res.data.host + '\r\n 结果：' + res.data.message
        })
      },
      complete(res) {
        wx.hideLoading()
      }
    })
  },
  ipItemLongTap(e) {
    const id = e.currentTarget.dataset.id
    const me = this
    wx.getSystemInfo({
      success: function(res) {
        console.log(res.platform)
        let itemList
        if(res.platform == 'android') {
          itemList = ['添加到定时检测','删除','取消']
        }else{
          itemList = ['添加到定时检测','删除']
        }
        wx.showActionSheet({
          itemList: itemList,
          success(res) {
            if(res.tapIndex === 0) {
              wx.request({
                url: app.globalData.host+ 'ip/addToCrontab',
                method: 'POST',
                data: {id: id,open_id: app.globalData.openId},
                success(res){
                  if(res.data.status === 'success'){
                    wx.showToast({
                      title: res.data.msg
                    })
                    me.getUserHost()
                  }else{
                    wx.showToast({
                      title: res.data.msg,
                      icon: 'none'
                    })
                  }
                  
                }
              })
            }
            if (res.tapIndex === 1) {
              me.delHost(id)
            }
          },
          fail(res) {
            console.log(res.errMsg)
          }
        })
      }
    })

    
  },
  setToTop(e) { //置顶操作
    let id = e.target.dataset.id
    let ids = this.getListIds()
    let ida = ids.split(",")
    let newIda = [id.toString()]
    for (var i = 0, n; n = ida[i]; i++) {
      if (n != id) {
        newIda.push(n)
      }
    }
    const newIds = newIda.toString()
    if (newIds != ids) {
      this.updateListOrder(newIds, true)
    } else {
      this.setData({
        modalName: null
      })
      wx.showToast({
        title: '已是人生巅峰',
        icon: 'none'
      })
    }
  },
  //以下是按住拖动事件
  dragStart: function (event) {
    var ids = this.getListIds()
    var startIndex = event.target.dataset.index
    // 初始化页面数据
    var pageInfo = this.data.pageInfo
    pageInfo.startY = event.touches[0].clientY
    pageInfo.readyPlaceIndex = startIndex
    pageInfo.selectedIndex = startIndex
    pageInfo.scrollY = false
    pageInfo.startIndex = startIndex

    this.setData({
      'movableViewInfo.y': pageInfo.startY - (pageInfo.rowHeight / 2)
    })
    // 初始化拖动控件数据
    var movableViewInfo = this.data.movableViewInfo
    movableViewInfo.data = this.data.userHost[startIndex]
    movableViewInfo.showClass = "inline"

    this.setData({
      movableViewInfo: movableViewInfo,
      pageInfo: pageInfo,
      ids: ids
    })
  },

  dragMove: function (event) {
    var list = this.data.userHost
    var pageInfo = this.data.pageInfo
    // 计算拖拽距离
    var movableViewInfo = this.data.movableViewInfo
    var movedDistance = event.touches[0].clientY - pageInfo.startY
    movableViewInfo.y = pageInfo.startY - (pageInfo.rowHeight / 2) + movedDistance

    // 修改预计放置位置
    var movedIndex = parseInt(movedDistance / pageInfo.rowHeight)
    var readyPlaceIndex = pageInfo.startIndex + movedIndex
    if (readyPlaceIndex < 0) {
      readyPlaceIndex = 0
    } else if (readyPlaceIndex >= list.length) {
      readyPlaceIndex = list.length - 1
    }

    if (readyPlaceIndex != pageInfo.selectedIndex) {
      var selectedData = list[pageInfo.selectedIndex]

      list.splice(pageInfo.selectedIndex, 1)
      list.splice(readyPlaceIndex, 0, selectedData)
      pageInfo.selectedIndex = readyPlaceIndex
    }
    // 移动movableView
    pageInfo.readyPlaceIndex = readyPlaceIndex

    this.setData({
      movableViewInfo: movableViewInfo,
      userHost: list,
      pageInfo: pageInfo
    })
  },

  dragEnd: function (event) {
    // 重置页面数据
    var pageInfo = this.data.pageInfo
    pageInfo.readyPlaceIndex = null
    pageInfo.startY = null
    pageInfo.selectedIndex = null
    pageInfo.startIndex = null
    pageInfo.scrollY = true
    // 隐藏movableView
    var movableViewInfo = this.data.movableViewInfo
    movableViewInfo.showClass = 'none'
    this.setData({
      pageInfo: pageInfo,
      movableViewInfo: movableViewInfo
    })
    const ids = this.getListIds()
    this.updateListOrder(ids)
  },
  //更新排序
  updateListOrder: function (ids, reload = false) {
    const me = this
    const open_id = app.globalData.openId
    if (this.data.ids != ids) {
      wx.request({
        url: app.globalData.host + 'ip/setUserHostSort',
        method: 'POST',
        data: { ids: ids, open_id: open_id },
        success(res) {
          if (reload) {
            me.getUserHost()
          }
          if (res.data.status === 'success') {
            wx.showToast({
              title: res.data.msg
            })
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        }
      })
    }
  },
  // 以下是左滑事件
  // ListTouch触摸开始
  ListTouchStart(e) {
    this.setData({
      ListTouchStart: e.touches[0].pageX
    })
  },

  // ListTouch计算方向
  ListTouchMove(e) {
    this.setData({
      ListTouchDirection: e.touches[0].pageX - this.data.ListTouchStart > 0 ? 'right' : 'left'
    })
    if (this.data.ListTouchDirection == 'left') {
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    } else {
      this.setData({
        modalName: null
      })
    }
  },

  // ListTouch计算滚动
  ListTouchEnd(e) {
    if (this.data.ListTouchDirection !== 'left') {
      this.setData({
        modalName: null
      })
    }
    this.setData({
      ListTouchDirection: null
    })
  },
  getListIds: function () {
    let ids = []
    const list = this.data.userHost
    for (let i = 0, n; n = list[i]; i++) {
      ids.push(n.id)
    }
    return ids.toString()
  }
})